/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datagram;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rmb
 */
public class Datagram {
 
    public enum UDPDatagram {
        CONNECT,
        DISCONNECT,
        ACK,
        FILENAME,
        DATA_TRANSFER,
        STOP_DATA_TRANSFER,
    }
    
    private UDPDatagram type;
    private int pack_num;
    private byte[] data;

    public Datagram(UDPDatagram type, int pack_num, byte[] data) {
        this.type = type;
        this.pack_num = pack_num;
        this.data = data;
    }
        
    public static byte[] toByteArray(Datagram d) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(d);
        }
        catch(IOException e) {}
        
        return bos.toByteArray();
    }
    
    public static Datagram byteToDatagram(byte[] buff) {
        Object obj = null;
        try {
            obj = new ObjectInputStream(new ByteArrayInputStream(buff)).readObject();
        } 
        catch (IOException ex) {} 
        catch (ClassNotFoundException ex) {}
        Datagram d = (Datagram) obj;
        return d;
    }
    
    public static Object byteToObject(byte[] buff) {
        
        Object obj = null;

        try {
            obj = new ObjectInputStream(new ByteArrayInputStream(buff)).readObject();
        }
        catch(IOException e) {}
        catch(ClassNotFoundException e) {}

        return obj;       
    }
    
    public byte[] getData() {
        return data;
    }

    public int getPack_num() {
        return pack_num;
    }

    public UDPDatagram getType() {
        return type;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public void setPack_num(int pack_num) {
        this.pack_num = pack_num;
    }

    public void setType(UDPDatagram type) {
        this.type = type;
    }
    
    
    
}
